<template>
  <div class="job-fairs-container">
    <xl-table :columns="columns" :action="loadData" ref="xlTableRef">
      <template slot="top">
        <el-button type="primary" size="small" style="margin-bottom: 10px" @click="dialogVisible = true">新增招聘会</el-button>
      </template>
      <template slot="image" slot-scope="{ row }">
        <img style="width: 200px; height: 100px" :src="row.image" alt="" />
      </template>
      <template slot="time" slot-scope="{ row }">
        <span>{{ parseTime(row.startTime, row.endTime) }}</span>
      </template>
      <template slot="companyTotal" slot-scope="{ row }">
        <span>{{ row.companys.length }}</span>
      </template>
      <template slot="jobTotal" slot-scope="{ row }">
        <span>{{ jobTotal(row.companys) }}</span>
      </template>
      <template slot="recruitStatus" slot-scope="{ row }">
        <span style="color: #67c23a" v-if="jobFairsStatus(row.startTime, row.endTime)">进行中</span>
        <span style="color: #f56c6c" v-else>已结束</span>
      </template>
      <template slot="enableStatus" slot-scope="{ row }">
        <span style="color: #67c23a" v-if="row.enableStatus === 1">展示</span>
        <span style="color: #f56c6c" v-else>隐藏</span>
      </template>
      <template slot="action" slot-scope="{ row }">
        <el-button type="text" @click="handleEditJobFairs(row)">编辑</el-button>
      </template>
    </xl-table>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="35%" @close="resetForm('jobFairsFormRef')">
      <el-form ref="jobFairsFormRef" :model="jobFairsForm" :rules="rules" label-width="120px" size="small">
        <el-form-item label="宣传海报：" prop="image">
          <el-upload
            class="upload-demo"
            drag
            action=""
            :show-file-list="false"
            :http-request="handleUploadFile"
            :before-upload="handleBeforeUpload"
          >
            <img v-if="jobFairsForm.image" :src="jobFairsForm.image" style="width: 100%; height: 100%" />
            <div v-else>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="标题：" prop="title">
          <el-input v-model="jobFairsForm.title" style="width: 350px"></el-input>
        </el-form-item>
        <el-form-item label="举办时间：" prop="startTime">
          <el-date-picker
            v-model="jobFairsTime"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="datePickerChange"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="举办地点：" prop="address">
          <el-input v-model="jobFairsForm.address" style="width: 350px"></el-input>
        </el-form-item>
        <el-form-item label="状态：">
          <el-radio-group v-model="jobFairsForm.enableStatus">
            <el-radio :label="1">展示</el-radio>
            <el-radio :label="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="handleSubmit('jobFairsFormRef')">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { columns } from './const'
import { getCredential, uploadFile } from '@/api/common'
import { getJobFairsList, createJobFairs, updateJobFairs } from '@/api/job-fairs'
import { parseTime } from '@/utils/index'

export default {
  name: 'JobFairsIndex',
  data() {
    return {
      columns,
      dialogVisible: false,
      dialogTitle: '新增招聘会',
      jobFairsId: null,
      jobFairsTime: [],
      jobFairsForm: {
        image: '',
        title: '',
        startTime: '',
        endTime: '',
        address: '',
        enableStatus: 1
      },
      rules: {
        image: { required: true, trigger: 'blur', message: '请上传招聘会宣传图' },
        title: { required: true, trigger: 'blur', message: '请输入招聘会标题' },
        startTime: { required: true, trigger: 'change', message: '请选择招聘会举办时间' },
        address: { required: true, trigger: 'blur', message: '请选择招聘会举办地点' }
      }
    }
  },
  methods: {
    // 编辑
    handleEditJobFairs(row) {
      this.jobFairsForm = { ...row }
      this.jobFairsId = row.id
      this.jobFairsTime = [row.startTime, row.endTime]
      this.dialogTitle = '编辑招聘会信息'
      this.dialogVisible = true
    },
    // 添加招聘会
    handleSubmit(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let res
          let message
          if (this.jobFairsId !== null) {
            res = await updateJobFairs(this.jobFairsForm)
            message = '添加成功'
          } else {
            res = await createJobFairs(this.jobFairsForm)
            message = '更新成功'
          }

          if (res.code === 200) {
            this.$message.success(message)
            this.dialogVisible = false
            this.$refs['xlTableRef'].loadData()
          }
        } else {
          return false
        }
      })
    },
    // 选择举办时间
    datePickerChange(e) {
      this.jobFairsForm.startTime = e[0]
      this.jobFairsForm.endTime = e[1]
    },
    // 上传图片
    async handleUploadFile(file) {
      const name = file.file.name
      const suffix = name.substr(name.lastIndexOf('.') + 1)
      const { data } = await getCredential(suffix, 'banner')
      const url = await uploadFile(data, file.file)
      this.jobFairsForm.image = url
    },
    // 上传图片前验证
    handleBeforeUpload(file) {
      const isFormat = /^image\/(png|jpeg|gif|bmp)$/.test(file.type)
      const isSize = file.size / 1024 / 1024 <= 5

      if (!isFormat) {
        this.$message.error('上传图片只能是 JPG、PNG、GIF 或 BMP 格式！')
      }

      if (!isSize) {
        this.$message.error(`上传图片大小不能超过 ${5}MB！`)
      }

      return isFormat && isSize
    },
    // 格式化时间
    parseTime(startTime, endTime) {
      const start = parseTime(new Date(startTime), '{y}-{m}-{d}')
      const end = parseTime(new Date(endTime), '{y}-{m}-{d}')
      return `${start} 至 ${end}`
    },
    // 计算岗位数量
    jobTotal(companys) {
      let total = 0
      companys.forEach((comp) => {
        total += comp.jobs.length
      })
      return total
    },
    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.dialogVisible = false
      this.dialogTitle = '新增招聘会'
      this.jobFairsId = null
      this.jobFairsTime = []
    },
    loadData(params) {
      return getJobFairsList(params)
    }
  }
}
</script>

<style lang="scss" scoped>
.job-fairs-container ::v-deep .el-upload-dragger {
  border-radius: 0px;
  width: 350px;
  height: 175px;
}
</style>
